﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace SuperMarKet
{
    class DBHelper
    {
        //创建数据库连接字符串
        public static string connString = "Data Source=.;Initial Catalog=SuperMarket;Integrated Security=True";
        //创建数据库连接对象
        private static SqlConnection conn = null;

        //初始化数据库连接
        private static void InitConnection()
        {
            if (conn == null)
                conn = new SqlConnection(connString);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            if (conn.State == ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
        }

        //增改删，返回结果true/false
        public static bool ExecuteNonQuery(string sqlStr)   //返回第一行
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, conn);
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result > 0;
        }

        //查询获取DataReader
        public static SqlDataReader GetDataReader(string sqlstr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        //查询获取DataSet
        public static DataSet GetDataSet(string sql)
        {
            InitConnection();
            SqlDataAdapter dap = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            return ds;
        }
        //查询获取DataTable
        public static DataTable GetdataTable(string sqlstr)
        {
            return GetDataSet(sqlstr).Tables[0];
        }
        //执行集合函数
        public static int ExecuteScalar(string sqlstr)  //返回第一行的第一列
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            int num = (int)cmd.ExecuteScalar();
            conn.Close();
            return num;
        }
    }
}
